# 读写文件 把大象放进冰箱
# 1. 打开文件
f = open('./test.txt', 'r', encoding='utf8')


# 2. 读写文件 读写方式 1) 文本读 r   2）文本写 w 3) 二进制读 rb 4) 二进制写 rw 5) 追加写 a
# 读
# 2.1 一次性读
# print(f.read())

# 2.2 一行一行的读
def readByLine():
    # print(f.readline())
    while True:
        data = f.readline()
        if len(data) == 0:
            break
        print(data)


# readByLine()

# 2.2 将读取多行数据放到列表中
def readAndPutList():
    data = f.readlines()
    for d in data:
        print(d)


readAndPutList()


# 写
# 2.3
def writeNormal():
    f2 = open('./test.txt', 'a', encoding='utf8')
    f2.write('测试3\n')
    f2.writelines(['测试4\n', '测试5\n'])


# writeNormal()

# 2.4 with 语法糖
def writeUseWith():
    # 封装了自动close 文件
    with open('./test.txt', 'w', encoding='utf8') as f:
        f.write('测试3\n')
        f.writelines(['测试4\n', '测试5\n'])


writeUseWith()


# 2.5 二进制操作
def writeByBinary():
    # 封装了自动close 文件
    with open(r'D:\生活\images\logo.png', 'rb') as f:
        data = f.read()
        with open(r'D:\生活\images\logo_backup.png', 'wb') as ff:
            ff.write(data)


writeByBinary()

# 3. 关闭文件
f.close()
